package it.gius.pe.algorithm.gjk.shapes;

import org.jbox2d.common.Vec2;

import it.gius.pe.Shape.Polygon;
import it.gius.pe.Shape.witness.PolyPointWitness;
import it.gius.pe.Shape.witness.Witness;
import it.gius.pe.algorithm.gjk.IGjkContainedShape;
import it.gius.pe.algorithm.gjk.Simplex;

public class GjkPolygon extends GjkSingleShape implements IGjkContainedShape{

	private Polygon poly = null;
	//private int startPointIndex = 0;
	private PolyPointWitness witness;
	
	public GjkPolygon(Polygon poly) {
		super();
		this.poly = poly;

		witness = new PolyPointWitness();
	}

	@Override
	public Witness supportPoint(Vec2 d,Vec2 supportPoint) {
		int index = 0;

		float maxDistance =Vec2.dot(poly.getVertex(index), d);  

		for(int i=1; i<poly.getVerticesCount();i++)
		{
			float curValue = Vec2.dot(poly.getVertex(i), d);
			if(curValue > maxDistance)
			{
				index = i;
				maxDistance = curValue;
			}

		}

		supportPoint.set(poly.getVertex(index));
		
		witness.index = index;
		
		return witness;
	}

	@Override
	public int getDim() {

		return poly.getVerticesCount();
	}


	/*@Override
	public void getStartingPoint(int suggestedIndex,Vec2 result) {
		if(suggestedIndex >= 0 && suggestedIndex<= poly.getVerticesCount())
			//return poly.getVertex(suggestedIndex);
			result.set(poly.getVertex(suggestedIndex));
		else
			//return poly.getVertex(0);
			result.set(poly.getVertex(0));
	}*/
	
	@Override
	public void getStartingPoint(Witness witness, Vec2 result) {
		poly.fromWitnessToVec(witness, result);
	}
	
	@Override
	public Witness getWitnessInstance() {
		//PolyWitness wit = new PolyWitness();
		witness.index = 0;
		return witness;
	}
	
	
	@Override
	public Simplex getStartingSimplex() {
		simplex.vs[0].set(poly.getVertex(0));
		simplex.currentDim = Simplex.IS_0_SIMPLEX;
		return simplex;
	}

}
